package javaweb.filter;

import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import javaweb.util.CurrentHolder;
import javaweb.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

@Slf4j
@WebFilter
public class TokenFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //获取请求的url路径
        String url = request.getRequestURI(); // /emp/login

        //1.校验路径中是否包含login，如果包含，说明是登录操作，放行
        if(url.contains("/login")){
            log.info("登录操作，放行");
            filterChain.doFilter(request, response);
            return;
        }

        //2.从请求头中获取token
        String token = request.getHeader("token");

        //3.检验token是否存在，不存在则返回401
        if((token == null) || (token.isEmpty())){
            log.info("令牌不存在，返回401状态码");
            response.setStatus(401);
            return;
        }

        //4.解析token，如果解析失败则返回401
        try {
            //从TreadLocal中存储当前员工的id，并传递给过滤器,AOP
            Claims claims = JwtUtils.parseJWT(token);
            Integer empId = Integer.valueOf(claims.get("id").toString());
            CurrentHolder.setCurrentId(empId);

        } catch (Exception e) {
            e.printStackTrace();
            log.info("令牌解析失败，返回401状态码");
            response.setStatus(401);
            return;
        }

        //5.放行
        log.info("令牌合法，放行");
        filterChain.doFilter(request, response);

        //删除ThreadLocal资源
        CurrentHolder.remove();
    }
}
